package com.test;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

import thrid.internet.GlideApp;
import thrid.internet.LoadImage;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView imageView;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        init();
    }

    private void init() {
        imageView = findViewById(R.id.imageView);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        loadImage();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1: //重新加载图片
                loadImage();
                break;
            case R.id.button2: //清除缓存
                GlideApp.get(MainActivity.this).clearMemory();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        GlideApp.get(MainActivity.this).clearDiskCache();
                        deleteDir(mContext.getCacheDir());
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            deleteDir(mContext.getExternalCacheDir());
                        }
                    }
                }).start();
                break;
        }
    }

    private void loadImage() {
        String url = "https://luxchange.oss-cn-beijing.aliyuncs.com/sap/J000040941-(1).jpg";
//        url = "https://mj-oss-test.oss-cn-beijing.aliyuncs.com/upload/image/201712/83e7a931-0f56-4413-a383-5e31c972bbdf.png";
        url = "http://luxchange.oss-cn-beijing.aliyuncs.com/upload/image/201806/f3d3c344-2834-4df9-8eeb-ddd85a150697.jpg";
        LoadImage.in().loadImage(this, url, imageView);
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}
